package com.aos.service;

import com.aos.client.GetUserTokenClient;
import com.aos.entity.JWT;
import com.aos.exception.CommonException;
import com.aos.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * Created by quxiaoyan
 */
@Service
public class UserEntryService {

    @Autowired
    GetUserTokenClient getUserTokenClient;

    /**
     * 获取Token
     * @param
     * @param password
     * @return token
     */
    public String getToken(String userId,String password,String serviceId,String secret,String type) throws UnsupportedEncodingException {

        System.out.println("==========调用开始=========");
        /*Base64编码*/
        //final Base64.Decoder decoder = Base64.getDecoder();
        final Base64.Encoder encoder = Base64.getEncoder();

        //获取token要校验ClientId和secret，先拼接为ClientId:secret形式
        final String text = serviceId + ":" + secret;
        final byte[] textByte = text.getBytes("UTF-8");

        //编码
        final String encodedText = encoder.encodeToString(textByte);
        System.out.println("=================text:[" + text + "]");
        System.out.println("=================textByte:[" + textByte + "]");
        System.out.println("=================encodedText:[" + encodedText + "]");
        System.out.println("=================type:[" + type + "]");
        System.out.println("=================userId:[" + userId + "]");
        System.out.println("=================password:[" + password + "]");

        //解码
//		System.out.println("第一个[" + new String(decoder.decode("dWFhLXNlcnZpY2U6MTIzNDU2"), "UTF-8") + "]");

        System.out.println("=========开始获取Token================");
        //获取Token
        JWT jwt = getUserTokenClient.getToken("Basic " + encodedText,type,userId,password);

        //JWT jwt = getUserTokenClient.getToken("Basic " + encodedText,"password","miya","123456");
        //JWT jwt = new JWT();
        if(null==jwt){
            throw new CommonException(ErrorCode.GET_TOKEN_FAIL);
        }
        System.out.println("=========获取的Token:" + jwt.getAccess_token());
        return jwt.getAccess_token();


        //return getUserTokenClient.req();
    }
}
